<?php

namespace App\Models\Admin;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Common\ValidateHandler;
use App\Models\Admin\Store;
use App\Models\Admin\Role;
use App\Common\Geetestlib;
use Carbon\Carbon;
use Config, Auth, JWTAuth;

class Admin extends Authenticatable implements JWTSubject
{
    protected $fillable = [
        'id', 'title', 'username', 'store_id', 'status',
        'role_id', 'password', 'created_at', 'updated_at'
    ];

    protected function serializeDate(\DateTimeInterface $date)
    {
        return Carbon::instance($date)->toDateTimeString();
    }

    use Notifiable;

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function getAvatarAttribute()
    {
        return Config::get('app.admin_url').'/user.png';
    }

    public function getGeetCode()
    {
        $geetestCode = Geetestlib::getGeetest();

        return $this->success(['geetest' => $geetestCode]);
    }

    public function getInfo()
    {
        $user = Auth::guard('admin')->user();

        return $this->success([
            'name' => $user->title,
            'avatar' => $user->avatar,
            'roles' => ['store_title' => $this->store_title, 'store_id' => $user->store_id]
        ]);
    }

    public function login($request)
    {
        $name = $request["username"];
        $password = $request["password"];

        $geetest_challenge = $request['geetest_challenge'];
        $geetest_validate = $request['geetest_validate'];
        $geetest_seccode = $request['geetest_seccode'];
        $gtServer = $request['gtServer'];
        $geetestArr = [
            "geetest_challenge" => $geetest_challenge,
            "geetest_validate" => $geetest_validate,
            "geetest_seccode" => $geetest_seccode,
            "gtServer" => $gtServer
        ];

        //极限二次认证 防刷
        $res = Geetestlib::validateGeetest($geetestArr);
        if(!$res){
            return $this->error(['info' => '请先获取验证码']);
        }

        $param = ['username'=>$name,'password'=>$password];
        $token = Auth::guard('admin')->attempt($param);
        $user = Auth::guard('admin')->user();
        if(!$token){
            return $this->error(['info' => '邮箱或者密码不正确']);
        }
        if ($user->status != 1) {
            return $this->error(['info' => '此用户已被禁用，请联系管理员']);
        }

        $role = Role::find($user->role_id);
        if ($role->status != 1) {
            return $this->error(['info' => '此角色已被禁用，请联系管理员']);
        }

        if($token){
            return $this->success(['token' => $token]);
        }
        return $this->error(['info' => '邮箱或者密码不正确']);
    }

    public function getList($pageSize)
    {
        $data = $this->paginate($pageSize);
        $data = $this->handleData($data);

        return $this->success($data);
    }

    private function handleData($data)
    {
        foreach ($data as $k => $user) {
            $data[$k]['store'] = $user->store_title;
            $data[$k]['role'] = $user->role_title;
        }

        return $data;
    }

    public function handle($data)
    {

        $arr = [];
        $arr['id'] = $data['id'];
        $arr['title'] = $data['title'];
        $arr['username'] = $data['username'];
        $arr['password'] = $data['password'];
        $arr['store_id'] = empty($data['store_id']) ? 0 : $data['store_id'];
        $arr['status'] = $data['status'];
        $arr['role_id'] = $data['role_id'];

        $result = $this->validate($arr);
        if (!$result['res']) {
            return $this->error($result);
        }

        $arr['password'] = bcrypt($arr['password']);
        if ($arr['id'] == 'new') {
            unset($arr['id']);
            $this->create($arr);
        } else {
            $id = $arr['id'];
            $this->where('id', $id)->update($arr);
        }

        return $this->success(['info' => '操作成功']);
    }

    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '用户名称',
                'value' => $data['title'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            1 => [
                'name' => '登录名',
                'value' => $data['username'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            2 => [
                'name' => '密码',
                'value' => $data['password'],
                'func' => 'length_limit',
                'min' => 6,
                'max' => 12
            ],
            3 => [
                'name' => '用户角色',
                'value' => $data['role_id'],
                'func' => 'is_empty',
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function getStoreTitleAttribute()
    {

        if ($this->store_id == 0) return '无店铺';

        return Store::find($this->store_id)['title'];
    }

    public function getRoleTitleAttribute()
    {
        if ($this->role_id == 0) return '无角色';

        return Role::find($this->role_id)['title'];
    }

    public function deleteAction($id)
    {
        $this->where('id', $id)->delete();

        return $this->success(['info' => '操作成功']);
    }

    private function success($data=[])
    {
        return response()->json([
            'data'=>$data,
            'code'=>20000
        ]);
    }

    private function error($data, $code = 20001)
    {
        return response()->json([
            'data'=>$data,
            'code'=>$code
        ]);
    }

}
